package netty;

import cn.hutool.core.date.DateUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

@Slf4j
public class WebSocketCase {
    private static final int PORT = 8080;
    @Test
    public void socketServer(){
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(4);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            // 以块的方式去写
                            pipeline.addLast(new ChunkedWriteHandler());
                            // http在传输大数据量的时候是分段的，这也就是为啥当浏览器发大量数据时，会发出多次http请求
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            // 对应时websocket 它的数据是以帧的形式传递,2-浏览器请求ws://localhost:7777/hello 表示请求的uri
                            // 3-WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议，保持长连接
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                            
                            //自己的业务逻辑处理 handle
                            pipeline.addLast(new WebSocketHandle());
                        }
                    });
            log.error("服务器 准备完成");
            ChannelFuture future = serverBootstrap.bind(PORT).sync();

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
    public static class WebSocketHandle extends SimpleChannelInboundHandler<TextWebSocketFrame>{

        /**
         * @param ctx  
         * @param msg TextWebSocketFrame 表示是一个文本类型帧
         * @throws Exception
         */
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
            log.error("服务器接受的的消息：{}",msg.text());
            ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间-"+ DateUtil.now()+"-"+msg.text()));
        }

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            log.error("handlerAdded 被调用，"+ctx.channel().id().asLongText());
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            log.error("handlerRemoved 被调用，"+ctx.channel().id().asLongText());
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            log.error("异常发生：{}",cause.getMessage());
            ctx.close();
        }
    }
}
